package com.ruoyi.cms.event;

import com.ruoyi.cms.blog.domain.CmsBlog;
import com.ruoyi.cms.blog.service.ICmsBlogService;
import com.ruoyi.teach.domain.TeachStudent;
import com.ruoyi.teach.event.CustomStudentChangeEvent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.List;

@Slf4j
@Component
public class CustomStudentChangeEventListener {

    @Autowired
    private ICmsBlogService cmsBlogService;

    @Async
    @EventListener
    public void handleCustomEvent(CustomStudentChangeEvent event) {
        System.out.println("---Received CustomStudentChangeEvent - " + event.getMessage());
        updateStudentInfoInBlog(event.getTeachStudent());
    }

    //更新博客中对应的人的信息
    public void updateStudentInfoInBlog(TeachStudent student) {
        Long studentId = student.getStudentId();
        CmsBlog cmsBlog = new CmsBlog();
        cmsBlog.setStudentId(studentId.intValue());
        log.info("查询学生ID为{}的信息", studentId);
        List<CmsBlog> cmsBlogs = cmsBlogService.selectCmsBlogList(cmsBlog);
        if (cmsBlogs.isEmpty()) {
            log.info("未查询到任何博客记录中该学生ID为{}的数据", studentId);
            return;
        }
        CmsBlog blog = cmsBlogs.get(0);
        String studentName = blog.getStudentName();
        String studentSex = blog.getStudentSex();
        if (student.getSex().equals(studentSex) && student.getStudentName().equals(studentName)) {
            log.info("学生信息未改变");
            return;
        }
        cmsBlog.setStudentName(student.getStudentName());
        cmsBlog.setStudentSex(student.getSex());
        int count = cmsBlogService.updateCmsBlogByStudentId(cmsBlog);
        log.info("更新的数据量为{}", count);
    }
}
